function area(poly){
  return poly
    .diff((head, tail) => head.cross(tail))
    .scalarSum();
}

function centroid(poly){
  const polyArea = area(poly);

  if (area !== 0) {

    const xPairSums = poly.diff(({x: head}, {x:tail}) => (head + tail) * 2);
    const yPairSums = poly.diff(({y: head}, {y:tail}) => (head + tail) * 2);
    const crosses = poly.diff((head, tail) => head.cross(tail));
      
    const centroid = new Vec(0, 0);

    for (let i = 0; i < crosses.length; i++) {
      centroid.x += xPairSums[i] * crosses[i] / (6 * polyArea);
      centroid.y += yPairSums[i] * crosses[i] / (6 * polyArea);
    }
      
    return centroid;

  } else {
      return undefined;
  }
}
